package com.xiaoxi.buildermode.builder;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName TextBuilder
 * @Description
 * @Author xiaoxi
 * @Date 2023/3/12 15:54
 * @Version 1.0
 */
public class TextBuilder implements IBuilder {

    private FileOutputStream fileOutputStream;

    @Override
    public void makeTitle(String filename) {
        try {
            fileOutputStream = new FileOutputStream(filename + ".txt");
        } catch (FileNotFoundException e) {
            System.out.println("出现异常：" + e.getMessage());
        }
    }

    @Override
    public void makeString(String str) {
        try {
            fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8));
            fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            System.out.println("出现异常：" + e.getMessage());
        }
    }

    @Override
    public void makeItems(List<String> items) {
        try {
            for (String item : items) {
                fileOutputStream.write("\t".getBytes(StandardCharsets.UTF_8));
                fileOutputStream.write(item.getBytes(StandardCharsets.UTF_8));
                fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            System.out.println("出现异常：" + e.getMessage());
        }
    }

    @Override
    public void close() {
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            System.out.println("出现异常：" + e.getMessage());
        }
    }
}
